package com.jackstraw.tools.utils;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 所在包：com.jackstraw.tools.utils
 * 文件名：
 * 项目：tools
 * 功能描述：
 * 修改人：Xlz
 * 修改时间：2020-08-03 15:29
 */
public class MathExpressionUtil {

    /**
     * 执行数学表达式的字符串
     * @param expression 数据表达式字符串
     * @return
     */
    public static String executeExpression(String expression) {
        String result = executeExpression(expression, new HashMap<>());
        return result;
    }

    /**
     * 执行数学表达式的字符串
     * @param expression 数据表达式字符串
     * @param params 表达式中的参数值
     * @return
     */
    public static String executeExpression(String expression, Map<String, Object> params) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("javascript");
        String result = null;
        try {
            Iterator<Map.Entry<String, Object>> iterator = params.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> next = iterator.next();
                engine.put(next.getKey(), next.getValue());
            }
            Object eval = engine.eval(expression);
            result = eval.toString();
        } catch (ScriptException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        Map<String, Object> params = new HashMap<>();
        params.put("x", 5);
        params.put("y", 10);
        String result = executeExpression("x*(y+2)", params);
        System.out.println(result);
    }
}
